package com.gulimall.product.exception;

import com.gulimall.common.exception.BizCodeEnume;
import com.gulimall.common.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;


@RestControllerAdvice(basePackages = "com.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handValidException(MethodArgumentNotValidException e){

        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            Map<String, String> map = new HashMap<>();
            bindingResult.getFieldErrors().forEach((item) -> {
                String field = item.getField();
                String message = item.getDefaultMessage();
                System.out.println(message);
                map.put(field,message);
            });
            return R.error(BizCodeEnume.VAILD_EXCEPTION).put("data",map);
        }
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handException(Throwable throwable){
        throwable.printStackTrace();
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION);
    }
}
